<template>
  <div class="goods-class">
    <!-- 搜索栏 -->
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="用户">
          <el-select filterable v-model="searchForm.userId" clearable placeholder="请选择用户">
            <el-option v-for="item,index in userList" :key="index" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券">
          <el-select filterable v-model="searchForm.couponId" clearable placeholder="请选择优惠券">
            <el-option v-for="item,index in couponList" :key="index" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="核销状态">
          <el-select filterable v-model="searchForm.writeOffStatus" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待核销" :value="0" />
            <el-option label="已核销" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="核销状态">
          <el-select filterable v-model="searchForm.refundStatus" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="未退款" :value="0" />
            <el-option label="已退款" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="退款申请状态">
          <el-select filterable v-model="searchForm.refundApplyStatus" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="未申请" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="审核通过" :value="2" />
            <el-option label="审核拒绝" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否过期">
          <el-select filterable v-model="searchForm.isExpired" placeholder="请选择是否过期">
            <el-option label="全部" value="" />
            <el-option label="未过期" :value="0" />
            <el-option label="已过期" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌店铺" prop="shopId">
          <el-select filterable v-model="searchForm.shopId" clearable placeholder="请选择品牌店铺" class="w-full">
            <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="exportData" v-has="'userCoupon:export'">导出</el-button>
  
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="orderNo" label="订单号" />
      <el-table-column prop="userId" label="用户id" />
      <el-table-column prop="couponId" label="优惠券id" />
      <el-table-column prop="shopId" label="商户id" />
      <el-table-column prop="orderNo" label="订单号" />
      <el-table-column prop="title" label="优惠券标题" />
      <el-table-column prop="paidAmount" label="实付金额" />
      <el-table-column prop="shopName" label="使用门店" />
      <el-table-column prop="shopAddress" label="使用门店地址" />
      <el-table-column prop="productStoreAddress" label="优惠券有效期">
        <template #default="{ row }">
          {{ row.effectStart }} - {{ row.effectEnd }}
        </template>
      </el-table-column>
      <el-table-column prop="writeOffNo" label="核销码" />
      <el-table-column prop="writeOffStatus" label="核销状态">
        <template #default="{ row }">
          <el-tag v-if="row.writeOffStatus === 0" type="danger">待核销</el-tag>
          <el-tag v-if="row.writeOffStatus === 1" type="success">已核销</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="refundStatus" label="退款状态">
        <template #default="{ row }">
          <div>{{row.refundStatus == 1 ? '已退款' : '未退款'}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="refundStatus" label="退款申请状态">
        <template #default="{ row }">
          <div>{{row.refundApplyStatus == 0 ? '未申请' : row.refundApplyStatus == 1 ? '待审核' : row.refundApplyStatus == 2 ?
            '审核通过' : row.refundApplyStatus == 3 ? '审核拒绝' : row.refundApplyStatus == 4 ? '已取消': '未发起退款' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="refundReason" label="退款申请原因" />
      <el-table-column prop="refundRemark" label="退款说明" />
      <el-table-column prop="writeOffTime" label="核销时间" />
      <el-table-column prop="writeOffBy" label="核销人" />
      <el-table-column prop="writeOffByNickname" label="核销人昵称" />
      <el-table-column label="操作" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleAudits(scope.row)" v-if="scope.row.refundApplyStatus == 1" v-has="'userCoupon:refundAudit'">退款审核</el-button>
        </template>
      </el-table-column>
  
    </el-table>
    <el-dialog title="退款审核" :visible.sync="auditVisible" width="500px" :close-on-click-modal="false"
      @closed="$refs.auditForm.resetFields()">
      <el-form :model="auditForm" :rules="auditRules" ref="auditForm" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input type="textarea" v-model="auditForm.remark" placeholder="请输入审核备注（选填）" :rows="4" maxlength="200"
            show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAudit">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </div>
    </el-dialog>
  
    <!-- 分页 -->
    <div style="text-align: right; margin-top: 16px;">
      <el-pagination :current-page="searchForm.page" :page-size="searchForm.pageSize" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>
  
  <script>
import { Loading } from 'element-ui';
export default {
  name: 'GoodsClass',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        page: 1,
        pageSize: 10,
        userId: '',
        couponId: '',
        writeOffStatus: '',
        isExpired: '',
        shopId: '',
        refundApplyStatus: ''
      },
      // 表格数据
      tableData: [],
      total: 10,
      loading: false,
      merchantList: [],
      userList: [],
      couponList: [],
      // ... 其他已有数据
      auditVisible: false,      // 控制审核弹窗显示
      auditForm: {
        status: 1,              // 1: 通过, 2: 拒绝
        remark: '',             // 审核备注
        id: null                // 当前操作的记录ID
      },
      auditRules: {
        status: [
          { required: true, message: '请选择审核结果', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.queryUserList()
    this.queryCouponList()
    this.getMerchantList()
  },
  methods: {
    // 打开审核弹窗
    handleAudits(row) {
      console.log(row, 'row');
      this.auditForm.id = row.id;
      this.auditForm.status = 1;  // 默认选择通过
      this.auditForm.remark = '';
      this.auditVisible = true;
    },

    // 提交审核
    submitAudit() {
      this.$refs.auditForm.validate(valid => {
        if (valid) {
          if(this.auditForm.status == 3 && !this.auditForm.remark) {
            return this.$message.error('请填写拒绝原因');
          }
          // 这里替换为您的实际API调用
          const params = {
            id: this.auditForm.id,
            auditStatus: this.auditForm.status,
            auditRemark: this.auditForm.remark
          };
          const loading = this.$loading({
          lock: true,
          text: '申请中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
         });    
          // 示例API调用
          this.$api.refundAudit(params).then(res => {
            console.log(res, '审核结果');
            this.$message.success('审核操作成功');
            this.auditVisible = false;
            loading.close();
            this.getList(); // 刷新列表
          }).catch(err => {
            loading.close();
            console.error(err);
            this.$message.error('操作失败');
          });
        }
      });
    },

    // 取消审核
    cancelAudit() {
      this.auditVisible = false;
      this.$refs.auditForm.resetFields();
    },
    async getMerchantList() {
      const { data } = await this.$api.shopPageList({
        page: 1,
        size: 10000,
        condition: {
          categoryId: '',
          areaId: '',
          floorId: '',
        }
      })
      // console.log(data, '111111');
      this.merchantList = data.result.records
    },
    async exportData() {
      // 显示加载中
      const loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 准备导出参数
        const params = {
          page: this.searchForm.page,
          size: this.searchForm.pageSize,
          condition: {
            userId: this.searchForm.userId,
            couponId: this.searchForm.couponId,
            writeOffStatus: this.searchForm.writeOffStatus,
            isExpired: this.searchForm.isExpired,
            shopId: this.searchForm.shopId
          }
        };

        // 调用导出API
        const { data } = await this.$api.exportUserCoupon(params);

        // 创建下载链接
        if (data) {
          // 如果返回的是文件流
          if (data instanceof Blob) {
            const blob = new Blob([data]);
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = '用户优惠券数据.xlsx'; // 设置下载文件名
            link.click();
            window.URL.revokeObjectURL(url);
            this.$message.success('导出成功');
          }
          // 如果返回的是下载链接
          else if (typeof data === 'string') {
            this.$message.success('导出成功');
            window.open(data, '_blank');
          }
          // 如果返回的是其他格式的数据
          else {
            this.$message.success('导出成功');
            console.log(data, '导出数据');
          }
        } else {
          this.$message.warning('没有可导出的数据');
        }
      } catch (error) {
        console.error('导出失败', error);
        this.$message.error('导出失败：' + (error.message || '未知错误'));
      } finally {
        // 关闭加载中
        loading.close();
      }
    },
    async queryCouponList() {
      const { data } = await this.$api.couponList({
        page: 1,
        size: 1000,
        condition: {
          categoryId: '',
          shelf: ''
        }
      })
      console.log(data, 'data');
      this.couponList = data.result.records
    },
    async queryUserList() {
      const { data } = await this.$api.getUserLists({
        page: 1,
        size: 1000,
        condition: {
          nickname: '',
          phone: '',
          status: '',
          type: 1
        }
      })
      this.userList = data.result.records
      console.log(data, '商户列表');
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.getUserCouponList({
          page: this.searchForm.page,
          size: this.searchForm.pageSize,
          condition: {
            userId: this.searchForm.userId,
            couponId: this.searchForm.couponId,
            writeOffStatus: this.searchForm.writeOffStatus,
            isExpired: this.searchForm.isExpired,
            shopId: this.searchForm.shopId
          }
        })
        console.log(data, 'data');
        data.result.records.forEach(e => {
          e.writeOffTime = e.writeOffTime ? e.writeOffTime.replace(/T/, ' ') : ''
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleSearch() {
      this.searchForm.page = 1
      this.getList()
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.getList()
    },
    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        sort: 0
      }
    }
  }
}
  </script>
  
  <style lang="scss" scoped>
.goods-class {
    padding: 20px;
  }
</style>